package leetcode.linkedlist;

/**
 * 删除链表的倒数第N个节点
 * 给定一个链表，删除链表的倒数第 n 个节点，并且返回链表的头结点。
 * <p>
 * 示例：
 * <p>
 * 给定一个链表: 1->2->3->4->5, 和 n = 2.
 * <p>
 * 当删除了倒数第二个节点后，链表变为 1->2->3->5.
 * 说明：
 * <p>
 * 给定的 n 保证是有效的。
 * <p>
 * 进阶：
 * <p>
 * 你能尝试使用一趟扫描实现吗？
 */
public class Solution2 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode orign = head;
        int count = 1;
        while (orign.next != null) {
            count += 1;
            orign = orign.next;
        }
        System.out.println("个数：" + count);
        int index = 0;
        orign = head;
        count = count - n - 1;
        if (orign.next == null) {
            return null;
        } else {
            while (orign.next != null) {
                if (count < 0) {
                    head = orign.next;
                    break;
                }
                if (index++ == count) {
                    if (orign.next.next != null) {
                        orign.next = orign.next.next;
                    } else {
                        orign.next = null;
                    }
                } else {
                    orign = orign.next;
                }
            }
        }
        return head;
    }


    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode ll1 = new ListNode(2);
        //ListNode lll1 = new ListNode(3);
        //ListNode llll1 = new ListNode(4);
        l1.next = ll1;
        //ll1.next = lll1;
        //lll1.next = llll1;
        ListNode before = l1;
        while (before != null) {
            System.out.println(before.val);
            before = before.next;
        }
        System.out.println("after:");
        ListNode result = new Solution2().removeNthFromEnd(l1, 2);
        ListNode temp = result;
        while (temp != null) {
            System.out.println(temp.val);
            temp = temp.next;
        }
    }
}



